let express = require("express");
let router = express.Router();
var db = require("../db/db");
let fs = require("fs");
let path = require("path");
let multer = require("multer");
let mkdirp = require("mkdirp");
var xlsx = require("node-xlsx");

// 上传文件保存配置
const storage = multer.diskStorage({
  destination: async function (req, file, cb) {
    // 1. 获取当前日期
    let day = global.moment(new Date()).format("YYYYMMDD");

    // 2. 拼接目录
    let dir = path.join("upload", day);

    // 3. 按照日期生成图片存储目录 mkdirp是异步方法
    await mkdirp(dir);

    cb(null, dir);
  },
  filename: function (req, file, cb) {
    // 1. 获取文件后缀名
    let extName = path.extname(file.originalname);
    // 2. 生成随机文件名
    cb(null, getRamNumber() + extName);
  },
  // 限制文件上传大小
  limits: { fileSize: "50mb" },
});
const upload = multer({ storage: storage }).single("file");

function getRamNumber() {
  let result = "";
  for (let i = 0; i < 16; i++) {
    result += Math.floor(Math.random() * 16).toString(16);
    //获取0-15并通过toString转16进制
  }
  //默认字母小写,手动转大写
  return result.toUpperCase();
}

// 上传文件
router.post("/", upload, (req, res) => {
  var reg = /\\/g;
  console.log(req.file.path.replace(reg, "/"));
  if (!req.file) {
    //判断一下文件是否存在，也可以在前端代码中进行判断。
    res.jsonp({
      code: 400,
      message: "上传文件不能为空！",
    });
    return;
  } else {
    res.jsonp({
      code: 200,
      path: req.file.path.replace(reg, "/").replace(/^upload/, ""),
      message: "上传成功",
    });
  }
});

// 读取数据
router.get("/data", async (req, res, next) => {
  let ret = await db.query("select * from data where id=?", [req.query.id]);
  // console.log(ret);
  if (ret.length > 0) {
    datas = readFile(ret[0].fileurl);
    res.jsonp({
      code: datas ? 200 : 400,
      message: datas ? "数据读取成功" : "暂无数据",
      data: datas ? datas : null,
    });
  } else {
    res.jsonp({
      code: 400,
      message: "无数据",
    });
  }
});

// node-xlsx读取数据
function test(url) {
  // var fileurl = path.resolve(__dirname, "../public/设备数据.xls");
  // console.log("fileurl", fileurl);

  var obj = xlsx.parse(url);
  var excelObj = obj[0].data;
  console.log(excelObj);

  let data = {
    xinlv: [],
    tidong: [],
    huxilv: [],
  };
  excelObj.forEach((item) => {
    if (item[0] == "心率") {
      data.xinlv.push({
        type: item[0],
        value: item[1],
        time: item[2],
      });
    } else if (item[0] == "体动") {
      data.tidong.push({
        type: item[0],
        value: item[1],
        time: item[2],
      });
    } else if (item[0] == "呼吸") {
      data.huxilv.push({
        type: item[0],
        value: item[1],
        time: item[2],
      });
    }
  });

  // console.log("体动", arr);
  return data;
}

// fs读取数据
function readFile(url) {
  let dir = "upload" + url,
    //let dir = "upload" + "/20230206/9A7432C225A0D682.csv",
    data = fs.readFileSync(dir).toString().split("\r\n"),
    newArr = [];

  for (let i = 1; i < data.length; i++) {
    let item = data[i].split(","),
      type = ["体动", "心率", "呼吸", "心率变异性", "呼吸变异性"];
    if (type.includes(item[0])) {
      newArr.push({
        type: item[0],
        value: item[1],
        time: item[2],
      });
    }
  }
  console.log(newArr);
  return newArr;
}

// csv转xlsx

function csvXlsx(url, name) {
  // 读取csv数据
  data = fs.readFileSync(url).toString().split("\r\n");

  // 将读取的csv数据转换成node-xlsx的数据格式
  // 将读取的csv数据转换二维数组
  for (let i = 0; i < data.length; i++) {
    data[i] = data[i].split(",");
  }
  let xlsxObj = new Array({
    name: "睡眠数据",
    data,
  });
  //  xlsx.build(xlsxObj) 将数据转换为Buffer格式
  // 拼接文件写入路径
  let dod = path.join(__dirname, `../${url.slice(0, -4)}.xlsx`);
  // 写入xlsx文件
  fs.writeFileSync(dod, xlsx.build(xlsxObj), "binary");
}

module.exports = router;
